<template>
  <el-dialog
    class="gl_dialog_TitleLine gl_dl_footer"
    width="880px"
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :before-close="close"
  >
    <div v-loading="pageLoading">
      <el-tabs v-model="activeName">
        <el-tab-pane label="一对多" name="many">
          <el-form ref="manyForm" :model="manyForm" :rules="rules" class="gl_form_mini" size="mini" label-position="top">
            <el-row :gutter="60">
              <el-col :span="12">
                <el-form-item prop="classId" label="班级">
                  <el-select v-if="title == '编辑'" v-model="manyForm.classId" placeholder="请选择班级" style="width: 100%;" @change="changeClass">
                    <el-option v-for="item in classList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                  <span v-else>{{ classObj.name }}</span>
                </el-form-item>
              </el-col>
              <el-col v-if="title == '编辑'" :span="12">
                <el-form-item prop="courseDate" label="上课日期">
                  <el-date-picker
                    v-model="manyForm.courseDate"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择上课日期"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col :span="12">
                <el-form-item prop="courseId" label="课程">
                  <el-select v-model="manyForm.course" placeholder="请选择课程" value-key="id" style="width: 100%;" @change="changeCourse">
                    <el-option v-for="item in coursesList[activeName]" :key="item.id" :value="item" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="startHour" label="上课时间">
                  <el-select v-model="manyForm.time" class="gl_mr_10" placeholder="请选择上课时间" style="width: 86%;" @change="changeTime">
                    <el-option v-for="item in timeList" :key="item.id" :value="item.time" :label="item.time" />
                  </el-select>
                  <el-button type="text" @click="setTime">设置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col :span="12">
                <el-form-item prop="coach" label="教练">
                  <el-select v-model="manyForm.coachObj" placeholder="请选择教练" value-key="id" style="width: 100%;" @change="changeCoach">
                    <el-option v-for="item in coachList" :key="item.id" :value="item" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="classroomId" label="教室">
                  <el-select v-model="manyForm.classroom" class="gl_mr_10" value-key="id" placeholder="请选择教室" style="width: 86%;" @change="changeRoom">
                    <el-option v-for="item in roomList" :key="item.id" :value="item" :label="item.name" />
                  </el-select>
                  <el-button type="text" @click="addClassRoom">新增</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col :span="12">
                <el-form-item label="助教">
                  <el-select v-model="manyAssistant" multiple class="gl_mr_10" placeholder="请选择助教" style="width: 100%;">
                    <el-option v-for="item in manyAssistantList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item prop="description" label="上课内容">
              <el-input v-model="manyForm.description" type="textarea" placeholder="请输入上课内容" size="mini" maxlength="120" show-word-limit />
            </el-form-item>
            <el-row :gutter="60">
              <el-col>
                <div class="gl_mr_20 gl_dis_ib" style="width: 16%">
                  <el-form-item label="签到信息推送">
                    <el-radio-group v-model="manyForm.isPushCheckInInfo" @change="changeCheckInInfo">
                      <el-radio :label="true">开启</el-radio>
                      <el-radio :label="false">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
                <div class="gl_ml_20 gl_dis_ib" style="width: 30%">
                  <el-form-item label="选择签到信息推送模板" prop="checkInMessageTemplateId">
                    <el-select v-model="manyForm.checkInMessageTemplateId" :disabled="!manyForm.isPushCheckInInfo" placeholder="请选择模板" style="width: 100%">
                      <el-option v-for="item in checkInList" :key="item.id" :value="item.id" :label="item.name" />
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col>
                <div class="gl_mr_20 gl_dis_ib" style="width: 16%">
                  <el-form-item label="签退信息推送">
                    <el-radio-group v-model="manyForm.isPushCheckOutInfo" @change="changeCheckOutInfo">
                      <el-radio :label="true">开启</el-radio>
                      <el-radio :label="false">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
                <div class="gl_ml_20 gl_dis_ib" style="width: 30%">
                  <el-form-item label="选择签退信息推送模板" prop="checkOutMessageTemplateId">
                    <el-select v-model="manyForm.checkOutMessageTemplateId" :disabled="!manyForm.isPushCheckOutInfo" placeholder="请选择模板" style="width: 100%">
                      <el-option v-for="item in checkOutList" :key="item.id" :value="item.id" :label="item.name" />
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col>
                <div class="gl_mr_20 gl_dis_ib" style="width: 16%">
                  <el-form-item label="预约设置">
                    <el-radio-group v-model="manyForm.canReserve" @change="changeReserve">
                      <el-radio :label="true">开启</el-radio>
                      <el-radio :label="false">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
                <div class="gl_ml_20 gl_dis_ib" style="width: 30%">
                  <el-form-item prop="reservationCount" label="预约人数">
                    <el-input v-model="manyForm.reservationCount" size="mini" placeholder="请输入预约人数" />
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col>
                <el-form-item label="预约规则">
                  <el-radio-group v-model="manyForm.isLimitReserveTime" class="gl_mr_20">
                    <el-radio :label="true">限制</el-radio>
                    <el-radio :label="false">关闭</el-radio>
                  </el-radio-group>
                  <div class="gl_ml_20 gl_dis_ib">
                    <span class="gl_pr_5">上课前</span>
                    <el-input v-model="manyForm.latestReserveTime" :disabled="!manyForm.isLimitReserveTime" style="width: 120px" size="mini" />
                    <span class="gl_pl_5">小时不可预约</span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col>
                <el-form-item label="取消规则">
                  <el-radio-group v-model="manyForm.isLimitCancleTime" class="gl_mr_20">
                    <el-radio :label="true">限制</el-radio>
                    <el-radio :label="false">关闭</el-radio>
                  </el-radio-group>
                  <div class="gl_ml_20 gl_dis_ib">
                    <span class="gl_pr_5">上课前</span>
                    <el-input v-model="manyForm.latestCancelTime" :disabled="!manyForm.isLimitCancleTime" style="width: 120px" size="mini" />
                    <span class="gl_pl_5">小时不可取消</span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="一对一" name="one">
          <el-form ref="oneForm" :model="oneForm" :rules="rules" class="gl_form_mini" size="mini" label-position="top">
            <el-row :gutter="60">
              <el-col :span="12">
                <el-form-item prop="classId" label="班级">
                  <el-select v-if="title == '编辑'" v-model="oneForm.classId" placeholder="请选择班级" style="width: 100%;" @change="changeClass">
                    <el-option v-for="item in classList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                  <span v-else>{{ classObj.name }}</span>
                </el-form-item>
              </el-col>
              <el-col v-if="title == '编辑'" :span="12">
                <el-form-item prop="courseDate" label="上课日期">
                  <el-date-picker
                    v-model="oneForm.courseDate"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    placeholder="请选择上课日期"
                    style="width: 100%;"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col :span="12">
                <el-form-item prop="courseId" label="课程">
                  <el-select v-model="oneForm.course" placeholder="请选择课程" value-key="id" style="width: 100%;" @change="changeCourse">
                    <el-option v-for="item in coursesList[activeName]" :key="item.id" :value="item" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="startHour" label="上课时间">
                  <el-select v-model="oneForm.time" class="gl_mr_10" placeholder="请选择上课时间" style="width: 86%;" @change="changeTime">
                    <el-option v-for="item in timeList" :key="item.id" :value="item.time" :label="item.time" />
                  </el-select>
                  <el-button type="text" @click="setTime">设置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col :span="12">
                <el-form-item prop="coach" label="教练">
                  <el-select v-model="oneForm.coachObj" placeholder="请选择教练" value-key="id" style="width: 100%;" @change="changeCoach">
                    <el-option v-for="item in coachList" :key="item.id" :value="item" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="classroomId" label="教室">
                  <el-select v-model="oneForm.classroom" class="gl_mr_10" value-key="id" placeholder="请选择教室" style="width: 86%;" @change="changeRoom">
                    <el-option v-for="item in roomList" :key="item.id" :value="item" :label="item.name" />
                  </el-select>
                  <el-button type="text" @click="addClassRoom">新增</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col :span="12">
                <el-form-item label="助教">
                  <el-select v-model="oneAssistant" multiple class="gl_mr_10" placeholder="请选择助教" style="width: 100%;">
                    <el-option v-for="item in oneAssistantList" :key="item.id" :value="item.id" :label="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item prop="description" label="上课内容">
              <el-input v-model="oneForm.description" type="textarea" placeholder="请输入上课内容" size="mini" maxlength="120" show-word-limit />
            </el-form-item>
            <el-row :gutter="60">
              <el-col>
                <div class="gl_mr_20 gl_dis_ib" style="width: 16%">
                  <el-form-item label="签到信息推送">
                    <el-radio-group v-model="oneForm.isPushCheckInInfo" @change="changeCheckInInfo">
                      <el-radio :label="true">开启</el-radio>
                      <el-radio :label="false">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
                <div class="gl_ml_20 gl_dis_ib" style="width: 30%">
                  <el-form-item label="选择签到信息推送模板" prop="checkInMessageTemplateId">
                    <el-select v-model="oneForm.checkInMessageTemplateId" :disabled="!oneForm.isPushCheckInInfo" placeholder="请选择模板" style="width: 100%">
                      <el-option v-for="item in checkInList" :key="item.id" :value="item.id" :label="item.name" />
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col>
                <div class="gl_mr_20 gl_dis_ib" style="width: 16%">
                  <el-form-item label="签退信息推送">
                    <el-radio-group v-model="oneForm.isPushCheckOutInfo" @change="changeCheckOutInfo">
                      <el-radio :label="true">开启</el-radio>
                      <el-radio :label="false">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
                <div class="gl_ml_20 gl_dis_ib" style="width: 30%">
                  <el-form-item label="选择签退信息推送模板" prop="checkOutMessageTemplateId">
                    <el-select v-model="oneForm.checkOutMessageTemplateId" :disabled="!oneForm.isPushCheckOutInfo" placeholder="请选择模板" style="width: 100%">
                      <el-option v-for="item in checkOutList" :key="item.id" :value="item.id" :label="item.name" />
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col>
                <div class="gl_mr_20 gl_dis_ib" style="width: 16%">
                  <el-form-item label="预约设置">
                    <el-radio-group v-model="oneForm.canReserve" @change="changeReserve">
                      <el-radio :label="true">开启</el-radio>
                      <el-radio :label="false">关闭</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
                <div class="gl_ml_20 gl_dis_ib" style="width: 30%">
                  <el-form-item prop="reservationCount" label="预约人数">
                    <el-input v-model="oneForm.reservationCount" size="mini" placeholder="请输入预约人数" />
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col>
                <el-form-item label="预约规则">
                  <el-radio-group v-model="oneForm.isLimitReserveTime" class="gl_mr_20">
                    <el-radio :label="true">限制</el-radio>
                    <el-radio :label="false">关闭</el-radio>
                  </el-radio-group>
                  <div class="gl_ml_20 gl_dis_ib">
                    <span class="gl_pr_5">上课前</span>
                    <el-input v-model="oneForm.latestReserveTime" :disabled="!oneForm.isLimitReserveTime" style="width: 120px" size="mini" />
                    <span class="gl_pl_5">小时不可预约</span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="60">
              <el-col>
                <el-form-item label="取消规则">
                  <el-radio-group v-model="oneForm.isLimitCancleTime" class="gl_mr_20">
                    <el-radio :label="true">限制</el-radio>
                    <el-radio :label="false">关闭</el-radio>
                  </el-radio-group>
                  <div class="gl_ml_20 gl_dis_ib">
                    <span class="gl_pr_5">上课前</span>
                    <el-input v-model="oneForm.latestCancelTime" :disabled="!oneForm.isLimitCancleTime" style="width: 120px" size="mini" />
                    <span class="gl_pl_5">小时不可取消</span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <Time ref="time" :time-list="timeList" />
      <AddClassRoom ref="addClassRoom" :form-data="formData" :code="'createDialog'" :title="title" @refreshRoom="refreshRoom" />
    </div>
    <div slot="footer">
      <el-button size="mini" @click="close()">取 消</el-button>
      <el-button :loading="loading" size="mini" type="primary" @click="submit()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import { CopyData } from '@/lib/index';
import Time from './time.vue';
import AddClassRoom from '@/viewsHall/classroom/addClassRoom';
import validator from '@/lib/validate/index.js';
import {
  api_GET_ClubClass, // 获取班级列表
  api_GET_ClubClassId, // 获取单个班级信息(班级内的课程信息)
  api_GET_ClubClassroom, // 获取教室
  api_GET_ClubCoach, // 获取教练
  api_GET_ClubCourseScheduleTime, // 获取上课时间段设置
  api_GET_ClubMessageTemplate, // 获取模板列表
  api_PUT_ClubCourseScheduleId // 更新课表
} from '@/extend/api/hallswaggerApi/app.js';
import {
  CreateCourseScheduleInput,
  CreateClassroomInput // 新建教室
} from '@/lib/form/hall/swaggerForm.js';
export default {
  components: {
    Time,
    AddClassRoom
  },
  props: {
    classObj: {
      type: Object,
      default() {
        return {};
      }
    },
    week: {
      type: String,
      default: ''
    },
    createCourseTime: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      title: '', // '编辑'是发布成功后的编辑
      code: '', // 'edit'是发布前的编辑
      activeName: 'many',
      pageLoading: false,
      loading: false,
      initForm: {
        classId: null,
        courseId: null,
        classroomId: null,
        courseDate: null,
        startHour: null,
        startMinute: null,
        endHour: null,
        endMinute: null,
        description: null,
        checkInDateTime: null,
        checkOutDateTime: null,
        isRemind: false,
        remindTime: 0,
        canReserve: false,
        reservationCount: 0,
        isLimitReserveTime: false,
        latestReserveTime: 0,
        isLimitCancleTime: false,
        latestCancelTime: 0,
        isPushCheckInInfo: false,
        isPushCheckOutInfo: false,
        checkInMessageTemplateId: null,
        checkOutMessageTemplateId: null,
        courseEmployees: [], // 教练 + 助教
        coach: '', // 所选教练的id
        coachObj: {}, // 所选教练的信息
        time: '', // 上课时间
        course: {}, // 课程信息
        courseScheduleColor: '', // 课程背景颜色
        classroom: {}, // 所选教室信息
        week: '', // 周几
        isEdit: false, // 是否为发布前的编辑
        hourKey: '', // 时间坐标
        delKey: '' // 编辑、删除时最里层的坐标
      },
      oneForm: {}, // 一对一表单
      manyForm: {}, // 一对多表单
      classList: [], // 班级列表
      coursesList: { // 课程列表(一对一、一对多是课程的属性)
        one: [],
        many: []
      }, // 课程列表
      coachList: [], // 教练列表
      oneAssistantList: [], // 助教列表
      manyAssistantList: [], // 助教列表
      timeList: [], // 上课时间
      roomList: [], // 教室列表
      checkInList: [], // 签到模板列表
      checkOutList: [], // 签退模板列表
      oneAssistant: [], // 所选助教
      manyAssistant: [], // 所选助教
      rules: {
        classId: [validator.required('班级选择不能为空')],
        courseId: [validator.required('课程选择不能为空')],
        courseDate: [validator.required('上课日期不能为空')],
        startHour: [validator.required('上课时间不能为空')],
        coach: [validator.required('教练选择不能为空')],
        reservationCount: [],
        checkOutMessageTemplateId: [],
        checkInMessageTemplateId: []
      },
      formData: {}, // 新建教室
      editId: '', // 编辑的id
      editForm: new CreateCourseScheduleInput()
    };
  },
  computed: {
    ...mapState({
      tenantId: state => state.user.tenantId
    })
  },
  watch: {
    activeName: {
      immediate: true,
      handler(value) {
        // 预约
        if (this[value + 'Form'].canReserve) {
          this.rules.reservationCount.push(validator.required('预约人数不能为空'));
        } else {
          this.rules.reservationCount = [];
        }
        // 签到
        if (this[value + 'Form'].isPushCheckInInfo) {
          this.rules.checkInMessageTemplateId.push(validator.required('签到信息模板不能为空'));
        } else {
          this.rules.checkInMessageTemplateId = [];
        }
        // 签退
        if (this[value + 'Form'].isPushCheckOutInfo) {
          this.rules.checkOutMessageTemplateId.push(validator.required('签退信息模板不能为空'));
        } else {
          this.rules.checkOutMessageTemplateId = [];
        }
      }
    }
  },
  created() {
  },
  methods: {
    open(title, data, code, hourKey) {
      this.title = title;
      this.code = code;
      this.oneForm = JSON.parse(JSON.stringify(this.initForm));
      this.manyForm = JSON.parse(JSON.stringify(this.initForm));
      this.getCoach();
      this.getTime();
      this.dialogVisible = true;

      if (this.title === '编辑') { // 课表页面的编辑
        this.openTimeTableEdit(data);
      } else {
        this.getRoom(this.classObj.id);
        this.getCheckInTemplate();
        this.getCheckOutTemplate();
        this.getCourse();
        if (code === 'edit') { // 排课页面的编辑
          if (data.course.teachingModeCode === 'OneToMany') {
            this.activeName = 'many';
          } else {
            this.activeName = 'one';
          }
          // 教练、助教信息回显
          this[this.activeName + 'Assistant'] = [];
          data.courseEmployees.forEach(item => {
            if (item.courseEmployeeTypeCode === 'Coach') {
              // 教练
              this[this.activeName + 'Form'].coachObj = {
                id: item.employeeId,
                name: item.employee.name
              };
              this[this.activeName + 'Form'].coach = item.employeeId;
            } else {
              // 助教
              this[this.activeName + 'Assistant'].push(item.employeeId);
            }
          });
          this.changeCheckInInfo(data.isPushCheckInInfo);
          this.changeCheckOutInfo(data.isPushCheckOutInfo);
          // 记录当前编辑的数据的旧时间坐标
          this[this.activeName + 'Form'].hourKey = hourKey;

          CopyData(data, this[this.activeName + 'Form']);
          this.oneForm.isEdit = true;
          this.manyForm.isEdit = true;
        } else {
          // 排课页面的创建
          this.activeName = 'many';
          this.oneAssistant = [];
          this.manyAssistant = [];
        }
        this.oneForm.classId = this.classObj.id;
        this.manyForm.classId = this.classObj.id;
      }
    },
    // 课表页面的编辑
    openTimeTableEdit(data) {
      this.changeCheckInInfo(data.isPushCheckInInfo);
      this.changeCheckOutInfo(data.isPushCheckOutInfo);
      this.getClass();
      this.getCourse(data.classId);
      this.getRoom(data.classId);
      this.getCheckInTemplate();
      this.getCheckOutTemplate();
      // 签到签退模板回显
      this[this.activeName + 'Form'].checkInMessageTemplateId = data.checkInMessageTemplate && data.checkInMessageTemplate.id;
      if (data.checkInMessageTemplate && (!data.checkInMessageTemplate.isEnabled)) {
        // 模板被禁用，显示空
        this[this.activeName + 'Form'].checkInMessageTemplateId = '';
      }
      this[this.activeName + 'Form'].checkOutMessageTemplateId = data.checkOutMessageTemplate && data.checkOutMessageTemplate.id;
      if (data.checkOutMessageTemplate && (!data.checkOutMessageTemplate.isEnabled)) {
        // 模板被禁用，显示空
        this[this.activeName + 'Form'].checkOutMessageTemplateId = '';
      }
      // tab页
      if (data.courseTeachingModeCode === 'OneToMany') {
        this.activeName = 'many';
      } else {
        this.activeName = 'one';
      }
      CopyData(data, this[this.activeName + 'Form']);
      // 课程信息回显
      this[this.activeName + 'Form'].course = {
        id: data.courseId,
        name: data.courseName
      };
      // 教室信息回显
      this[this.activeName + 'Form'].classroom = {
        id: data.classroomId,
        name: data.classroomName
      };
      // 教练、助教信息回显
      this[this.activeName + 'Assistant'] = [];
      data.courseEmployees.forEach(item => {
        if (item.courseEmployeeTypeCode === 'Coach') {
          // 教练
          this[this.activeName + 'Form'].coachObj = {
            id: item.employeeId,
            name: item.employee.name
          };
          this[this.activeName + 'Form'].coach = item.employeeId;
        } else {
          // 助教
          this[this.activeName + 'Assistant'].push(item.employeeId);
        }
      });
      // 上课时间回显
      const startHour = data.startHour < 10 ? '0' + data.startHour : data.startHour;
      const endHour = data.endHour < 10 ? '0' + data.endHour : data.endHour;
      const startMinute = data.startMinute < 10 ? '0' + data.startMinute : data.startMinute;
      const endMinute = data.endMinute < 10 ? '0' + data.endMinute : data.endMinute;
      this[this.activeName + 'Form'].time = startHour + ':' + startMinute + '~' + endHour + ':' + endMinute;
      // 记录编辑的课表id
      this.editId = data.id;
    },
    // 关闭弹窗
    close() {
      this.dialogVisible = false;
      this.rules.checkInMessageTemplateId = [];
      this.rules.checkOutMessageTemplateId = [];
      this.$refs['oneForm'].resetFields();
      this.$refs['manyForm'].resetFields();
    },
    // 获取班级列表
    getClass() {
      var that = this;
      api_GET_ClubClass({ HasScheduledCourse: null, IncludeCourse: false, IncludeClassStudent: false }).then(res => {
        that.classList = res.items || [];
      }).catch(error => {
        that.$message({ type: 'error', message: error.error.message || '获取班级列表失败' });
      });
    },
    // 获取课程
    getCourse(classId) {
      var that = this;
      that.pageLoading = true;
      const id = that.classObj.id ? that.classObj.id : classId;
      that.coursesList = {
        one: [], // 一对一的课程
        many: [] // 一对多的课程
      };
      const form = {
        IncludeCourse: true,
        IncludeClassStudentCount: true
      };
      api_GET_ClubClassId(id, form).then(res => {
        const courses = res.courses || [];
        for (let i = 0; i < courses.length; i++) {
          const item = courses[i];
          if (item.teachingModeCode === 'OneToOne') {
            that.coursesList.one.push(item);
          } else {
            that.coursesList.many.push(item);
          }
        }
        that.pageLoading = false;
      }).catch(error => {
        that.pageLoading = false;
        that.$message({ type: 'error', message: error.error.message || '获取课程列表失败' });
      });
    },
    // 获取教练
    getCoach() {
      var that = this;
      that.pageLoading = true;
      const form = {
        CanTeach: true,
        IsEnabled: true
      };
      api_GET_ClubCoach(form).then(res => {
        that.coachList = res.items || [];
        that.oneAssistantList = res.items || [];
        that.manyAssistantList = res.items || [];
        if (that.title === '编辑' || that.code === 'edit') {
          // 助教下拉列表内不可含有教练
          that[that.activeName + 'AssistantList'] = JSON.parse(JSON.stringify(that.coachList));
          const key = that.coachList.findIndex(coach => coach.id === that[that.activeName + 'Form'].coach);
          that[that.activeName + 'AssistantList'].splice(key, 1);
        }
        that.pageLoading = false;
      }).catch(error => {
        that.pageLoading = false;
        that.$message({ type: 'error', message: error.error.message || '获取教练失败' });
      });
    },
    // 获取上课时间段
    getTime() {
      var that = this;
      api_GET_ClubCourseScheduleTime().then(res => {
        that.timeList = res || [];
        if (that.timeList.length > 0) {
          that.timeList = that.timeList.map(item => {
            const startHour = item.startHour < 10 ? '0' + item.startHour : item.startHour;
            const endHour = item.endHour < 10 ? '0' + item.endHour : item.endHour;
            const startMinute = item.startMinute < 10 ? '0' + item.startMinute : item.startMinute;
            const endMinute = item.endMinute < 10 ? '0' + item.endMinute : item.endMinute;
            const time = startHour + ':' + startMinute + '~' + endHour + ':' + endMinute;
            return { ...item, time: time, isEdit: false };
          });
        }
      }).catch(error => {
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 获取教室
    getRoom(classId) {
      var that = this;
      const form = {
        ClassId: classId
      };
      api_GET_ClubClassroom(form).then(res => {
        that.roomList = res.items || [];
      }).catch(error => {
        that.$message({ type: 'error', message: error.error.message });
      });
    },
    // 新建教室
    addClassRoom() {
      this.formData = {};
      this.$refs.addClassRoom.open();
      this.title = '新建教室';
      this.formData = new CreateClassroomInput();
    },
    // 更新教室列表
    refreshRoom() {
      this.getRoom(this[this.activeName + 'Form'].classId);
    },
    // 获取签到模板列表
    getCheckInTemplate() {
      var that = this;
      const form = {
        MessageTemplateTypeCode: 'CheckIn', // 签到
        IsEnabled: true,
        IncludeMessageTemplateType: true
      };
      api_GET_ClubMessageTemplate(form).then(res => {
        that.checkInList = res.items || [];
        // 课表页面的编辑
        if (that.title === '编辑' && that[that.activeName + 'Form'].checkInMessageTemplateId) {
          let whether = false;
          whether = that.checkInList.some(item => {
            return item.id === that[that.activeName + 'Form'].checkInMessageTemplateId;
          });
          if (!whether) {
            that[that.activeName + 'Form'].checkInMessageTemplateId = '';
          }
        }
      }).catch(error => {
        that.$message({ type: 'error', message: error.error.message || '获取模板列表失败' });
      });
    },
    // 获取签退模板列表
    getCheckOutTemplate() {
      var that = this;
      const form = {
        MessageTemplateTypeCode: 'CheckOut', // 签退
        IsEnabled: true,
        IncludeMessageTemplateType: true
      };
      api_GET_ClubMessageTemplate(form).then(res => {
        that.checkOutList = res.items || [];
        // 课表页面的编辑
        if (that.title === '编辑' && that[that.activeName + 'Form'].checkOutMessageTemplateId) {
          let whether = false;
          whether = that.checkOutList.some(item => {
            return item.id === that[that.activeName + 'Form'].checkOutMessageTemplateId;
          });
          if (!whether) {
            that[that.activeName + 'Form'].checkOutMessageTemplateId = '';
          }
        }
      }).catch(error => {
        that.$message({ type: 'error', message: error.error.message || '获取模板列表失败' });
      });
    },
    // 上课时间--设置
    setTime() {
      this.$refs.time.open();
    },
    // 班级选择器
    changeClass(val) {
      this.getCourse(val); // 班级改变后，重新获取课程
      this[this.activeName + 'Form'].course = {};
      this[this.activeName + 'Form'].courseId = '';
    },
    // 课程选择器
    changeCourse(val) {
      this[this.activeName + 'Form'].courseScheduleColor = val.courseScheduleColor; // 课程颜色
      this[this.activeName + 'Form'].courseId = val.id;
    },
    // 教练选择器
    changeCoach(val) {
      this[this.activeName + 'Form'].coach = val.id;
      // 当教练改变时，助教选择重置，助教下拉列表跟随变化（教练，助教不能为同一人）
      this[this.activeName + 'AssistantList'] = JSON.parse(JSON.stringify(this.coachList));
      this[this.activeName + 'Assistant'] = [];
      const key = this.coachList.findIndex(item => item.id === val.id);
      this[this.activeName + 'AssistantList'].splice(key, 1);
    },
    // 教室选择器
    changeRoom(val) {
      this[this.activeName + 'Form'].classroomId = val.id;
    },
    // 上课时间选择器
    changeTime(val) {
      const start = val.split('~')[0];
      const end = val.split('~')[1];
      this[this.activeName + 'Form'].startHour = start.split(':')[0];
      this[this.activeName + 'Form'].startMinute = start.split(':')[1];
      this[this.activeName + 'Form'].endHour = end.split(':')[0];
      this[this.activeName + 'Form'].endMinute = end.split(':')[1];
    },
    // 签到
    changeCheckInInfo(val) {
      if (val) {
        this.rules.checkInMessageTemplateId.push(validator.required('签到信息模板不能为空'));
      } else {
        this.rules.checkInMessageTemplateId = [];
      }
      this.$nextTick(() => {
        this.$refs[this.activeName + 'Form'].clearValidate('checkInMessageTemplateId');
      });
    },
    // 签退
    changeCheckOutInfo(val) {
      if (val) {
        this.rules.checkOutMessageTemplateId.push(validator.required('签退信息模板不能为空'));
      } else {
        this.rules.checkOutMessageTemplateId = [];
      }
      this.$nextTick(() => {
        this.$refs[this.activeName + 'Form'].clearValidate('checkOutMessageTemplateId');
      });
    },
    // 预约
    changeReserve(val) {
      if (val) {
        this.rules.reservationCount.push(validator.required('预约人数不能为空'));
      } else {
        this.rules.reservationCount = [];
      }
      this.$refs[this.activeName + 'Form'].clearValidate('reservationCount');
    },
    // 确定（关闭弹窗）
    submit() {
      var that = this;
      // code === 'edit' 是排课页面的编辑
      this.oneForm.week = this.code === 'edit' ? this.oneForm.week : this.week;
      this.manyForm.week = this.code === 'edit' ? this.manyForm.week : this.week;
      let arr = [];
      arr = this[this.activeName + 'Assistant'].map(item => {
        return {
          employeeId: item,
          courseEmployeeTypeCode: 'AssistantCoach'
        };
      });
      arr.push({
        employeeId: this[this.activeName + 'Form'].coach,
        courseEmployeeTypeCode: 'Coach',
        employee: {
          name: this[this.activeName + 'Form'].coachObj.name
        }
      });
      this[this.activeName + 'Form'].courseEmployees = arr; // 教练 + 助教
      // this[this.activeName + 'Form'].latestCancelTime = this[this.activeName + 'Form'].latestCancelTime === '' ? 0 : this[this.activeName + 'Form'].latestCancelTime;
      // this[this.activeName + 'Form'].latestReserveTime = this[this.activeName + 'Form'].latestReserveTime === '' ? 0 : this[this.activeName + 'Form'].latestReserveTime;
      // this[this.activeName + 'Form'].reservationCount = this[this.activeName + 'Form'].reservationCount === '' ? 0 : this[this.activeName + 'Form'].reservationCount;
      // this[this.activeName + 'Form'].remindTime = this[this.activeName + 'Form'].remindTime === '' ? 0 : this[this.activeName + 'Form'].remindTime;
      this.$refs[this.activeName + 'Form'].validate((valid) => {
        if (valid) {
          if (that.title !== '编辑') {
            // 排课页面
            if (that.code !== 'edit') {
              // 排课页面的创建
              that.$emit('getForm', that[that.activeName + 'Form']);
            } else {
              // 排课页面的编辑
              that.$emit('editForm', that[that.activeName + 'Form'], that.code);
            }
            that.close();
          } else {
            // 课表页面的编辑
            CopyData(that[that.activeName + 'Form'], that.editForm);
            api_PUT_ClubCourseScheduleId(that.editId, that.editForm).then(res => {
              that.loading = false;
              that.close();
              // 编辑成功后刷新课表
              that.$emit('refresh');
              that.$message({ type: 'success', message: '编辑成功' });
            }).catch(error => {
              that.loading = false;
              that.$message({ type: 'error', message: error.error.message || '编辑失败' });
            });
          }
        }
      });
    }
  }
};
</script>

